﻿using UIDesigner.SurfaceProperties;
using System.IO;
using System.Xml.Serialization;

public static class SavedSurfaceProperties
{
    private const string FILE_NAME = @"..\..\..\UIDesigner\PropertyGroups\PropertyGroups.config";
    private static SurfacePropertyGroups m_rgPropertyGroups;
    private static FileInfo m_objFile = new FileInfo(FILE_NAME);
    private static SurfacePropertiesBase m_objSelectedProperties;

    public static SurfacePropertiesBase SelectedProperties
    {
        get
        {
            LoadFile();

            foreach (SurfacePropertiesBase objSurfaceProperties in SavedSurfaceProperties.PropertyGroups)
            {
                if (objSurfaceProperties.Selected)
                {
                    m_objSelectedProperties = objSurfaceProperties;
                }
            }

            return SavedSurfaceProperties.m_objSelectedProperties;
        }

        set
        {
            m_objSelectedProperties = value;

            foreach (SurfacePropertiesBase objSurfaceProperties in SavedSurfaceProperties.PropertyGroups)
            {
                objSurfaceProperties.Selected = false;
            }

            if (m_objSelectedProperties != null)
            {
                m_objSelectedProperties.Selected = true;
            }

            SaveFile();
        }
    }

    public static string AppySelectedText
    {
        get
        {
            if (SavedSurfaceProperties.SelectedProperties == null)
            {
                return "(None Selected)";
            }
            else
            {
                return SavedSurfaceProperties.SelectedProperties.Name;
            }
        }
    }

    public static SurfacePropertyGroups PropertyGroups
    {
        get
        {
            if (m_rgPropertyGroups == null)
            {
                m_rgPropertyGroups = new SurfacePropertyGroups();
            }

            return m_rgPropertyGroups;
        }
    }

    public static bool FileExists
    {
        get
        {
            return m_objFile.Exists;
        }
    }

    public static void LoadFile()
    {
        XmlSerializer objSerializer;
        TextReader objReader;

        objSerializer = new XmlSerializer(typeof(SurfacePropertyGroups));
        objReader = new StreamReader(FILE_NAME);

        m_rgPropertyGroups = (SurfacePropertyGroups)objSerializer.Deserialize(objReader);
        objReader.Close();
    }

    public static void SaveFile()
    {
        XmlSerializer objSerializer;
        TextWriter objWriter;

        objSerializer = new XmlSerializer(typeof(SurfacePropertyGroups));
        objWriter = new StreamWriter(FILE_NAME);

        objSerializer.Serialize(objWriter, m_rgPropertyGroups);
        objWriter.Close();
    }
}
